package com.toivan.mt.fragment;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.hwangjr.rxbus.RxBus;
import com.shizhefei.fragment.LazyFragment;
import com.toivan.mt.R;
import com.toivan.mt.adapter.MtGreenScreenAdapter;
import com.toivan.mt.model.MtGreenScreen;
import com.toivan.mt.model.RxBusAction;
import com.toivan.mt.utils.MtCallback;
import com.toivan.mt.utils.MtJsonParser;
import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName GreenScreenFragment
 * @Description 绿幕的Fragment
 * @Author yang
 * @Date 2021/6/23 10:13
 */
public class MtGreenScreenFragment extends LazyFragment {

    private MtGreenScreenAdapter adapter;

    public List<MtGreenScreen> list = new ArrayList<>();

    private static final int IMAGE_REQUEST_CODE = 0;//标题图片的选中返回

    @Override
    protected void onCreateViewLazy(Bundle savedInstanceState) {
        super.onCreateViewLazy(savedInstanceState);
        setContentView(R.layout.fragment_sticker_recyclerview);
        list.clear();
        list.add(MtGreenScreen.NO_GREEN_SCREEN);
        List<MtGreenScreen> allGreenScreen = MtJsonParser.getInstance().getAllGreenScreen();

        if (allGreenScreen == null || allGreenScreen.size() == 1) {

            MtJsonParser.getInstance().getGreenScreens(new MtCallback<List<MtGreenScreen>>() {
                @Override
                public void callback(List<MtGreenScreen> bean) {
                    if (bean != null) {
                        list.addAll(bean);
                        showGreenScreen();
                        //同步删除按钮的状态
                        RxBus.get().post(RxBusAction.ACTION_SELECT_GREEN_SCREEN, "");
                    }
                }
            });
        } else {
            list.addAll(allGreenScreen);
            showGreenScreen();

            //同步删除按钮的状态
            RxBus.get().post(RxBusAction.ACTION_SELECT_GREEN_SCREEN, "");
        }
    }

    /**
     * 删除对应的item
     *
     * @param position 序列号
     */
    public void updateDelete(int position) {
        list.remove(list.get(position));
        //同步删除按钮的状态
        RxBus.get().post(RxBusAction.ACTION_SELECT_GREEN_SCREEN, "");
        adapter.syncNotifyDataChanged();
    }

    /**
     * 显示
     */
    public void showGreenScreen() {
        RecyclerView portraitRV = (RecyclerView) findViewById(R.id.recyclerView);
        adapter = new MtGreenScreenAdapter(list, new GreenScreenClick() {
            @Override
            public void clickGreenScreenFromDisk() {
                //调起相册
                openAlbum();
            }
        });
        portraitRV.setLayoutManager(new GridLayoutManager(getContext(), 5));
        adapter.setHasStableIds(true);
        portraitRV.setAdapter(adapter);
    }

    /**
     * 打开相册
     */
    private void openAlbum() {
        //检测权限
        if (ContextCompat.checkSelfPermission(requireContext(),
            Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(requireActivity(), new String[] {
                Manifest.permission.WRITE_EXTERNAL_STORAGE
            }, 1);
        }
        //调取系统相册
        Intent intent = new Intent(Intent.ACTION_PICK,
            android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(intent, IMAGE_REQUEST_CODE);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data == null || data.getData() == null) return;
        if (requestCode == IMAGE_REQUEST_CODE) {
            handleImageBeforeKitKat(data);
        }

    }

    /**
     * 取消选择
     */
    public void cancelGreenScreen() {
        if (adapter != null) {
            adapter.cancelSelected();
        }
    }

    public interface GreenScreenClick {
        //点击从相册中选择背景
        void clickGreenScreenFromDisk();

    }

    //对于获取用户图片选中的后处理
    private void handleImageBeforeKitKat(Intent data) {
        Uri uri = data.getData();
        if (uri == null) return;
        String imagePath = getImagePath(uri, null);
        if (!isPngOrJpg(imagePath)) {
            Toast.makeText(getContext(), "暂时只兼容png和jpg格式的背景图", Toast.LENGTH_SHORT).show();
            return;
        }
        MtGreenScreen mtGreenScreen = new MtGreenScreen("", "", "", "", true, true);
        mtGreenScreen.setFromDisk(true, requireContext(), imagePath);
        list.add(mtGreenScreen);
        adapter.selectItem(list.size() - 1);
        adapter.notifyDataSetChanged();
    }

    /**
     * @param uri 传过来的uri
     * @param selection 规则
     * @return 路径
     */
    private String getImagePath(@NonNull Uri uri, @Nullable String selection) {
        String path = null;
        Cursor cursor = requireActivity().getContentResolver().query(uri, null, selection, null, null);
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            }
            cursor.close();
        }
        return path;
    }

    /**
     * 用于判断格式是否正确
     *
     * @param path 路径
     * @return 结果
     */
    private boolean isPngOrJpg(String path) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(path, options);
        String type = options.outMimeType;
        Log.i("添加的绿幕的背景图格式：", options.outMimeType);
        return type.equals("image/png") || type.equals("image/jpg") || type.equals("image/jpeg");
    }

}

